// 封装函数
function myAxios(config) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    if (config.params) {
      const paramsObj = new URLSearchParams(config.params)
      const queryString = paramsObj.toString()
      config.url += `?${queryString}`
    }
    xhr.open(config.method || 'get', config.url)
    xhr.addEventListener('loadend', () => {
      if (xhr.status >= 200 && xhr.status < 300) {
        resolve(JSON.parse(xhr.response))
      } else {
        reject(new Error(xhr.response))
      }
    })
    if (config.headers) {
      Object.keys(config.headers).forEach(key => {
        xhr.setRequestHeader(key, config.headers[key])
      })
    }
    if (config.data instanceof FormData) {
      xhr.send(config.data)
    } else if (config.data) {
      xhr.setRequestHeader('Content-Type', 'application/json')
      xhr.send(JSON.stringify(config.data))
    } else {
      xhr.send()
    }
  })
}

// 登出
document.querySelector('.user a').addEventListener('click', () => {
  if (confirm('您确定要登出吗？')) {
    myAxios({
      url: 'https://blog.zifeiyu.love/user/logout',
      params: {
        token: localStorage.getItem('token')
      }
    }).then(() => {
      localStorage.removeItem('token')
      location.href = 'index.html'
    })
  }
})

// 登录后才能访问该页面
if (!localStorage.getItem('token')) {
  location.href = 'index.html'
}

// 右键修改密码
const box = document.querySelector('.background-shadow')
const closebtn = document.querySelector('.icon-shanchu1')
closebtn.addEventListener('click', () => {
  box.style.display = 'none'
})
const pwreg = /^(?=.*[a-z])[a-zA-Z0-9_]{6,}$/
const prev = document.querySelector('.password-prev')
const next = document.querySelector('.password-next')
document.querySelector('.user a').addEventListener('contextmenu', (e) => {
  e.preventDefault()
  box.style.display = 'block'
  document.querySelector('.login').addEventListener('click', () => {
    if (prev.value === next.value) {
      alert('密码还是一样的')
    } else if (pwreg.test(document.querySelector('.password-next').value)) {
      myAxios({
        url: 'https://blog.zifeiyu.love/info/change',
        params: {
          ordPass: prev.value,
          newPass: next.value
        },
        method: 'put',
        headers: {
          token: localStorage.getItem('token')
        }
      }).then(() => {
        localStorage.removeItem('token')
        location.href = 'index.html'
      }).catch(error => {
        console.log(error)
      })
    } else {
      alert('密码至少6位,且至少含一个小写字母')
    }
  })
})

// 根据左侧li决定右侧内容
document.querySelector('.user-list').addEventListener('click', (e) => {
  e.preventDefault()
  const li = e.target.closest('li')
  const items = document.querySelectorAll('aside .item')
  if (li) {
    document.querySelectorAll('.user-list .active').forEach(item => {
      item.classList.remove('active')
    })
    li.classList.add('active')
    const i = +li.dataset.id
    document.querySelector('aside .active').classList.remove('active')
    items[i].classList.add('active')
  }
})

// 观看历史顺序排列
let str = ''
if (localStorage.getItem('ids')) {
  JSON.parse(localStorage.getItem('ids')).forEach(item => {
    myAxios({
      url: 'https://blog.zifeiyu.love/video/query',
      params: {
        id: item
      },
      headers: {
        token: localStorage.getItem('token')
      }
    }).then(result => {
      str += `
          <div class="history-item">
            <img src="${result.data.cover}" alt="">
            <span>${result.data.name}</span>
          </div>
    `
      document.querySelector('.history-body').innerHTML = str
    })
  })
}


// 删除观看历史列表
document.querySelector('.delete').addEventListener('click', () => {
  document.querySelector('.history-body').innerHTML = ''
  localStorage.removeItem('liStr')
  localStorage.removeItem('ids')
})

// 收藏记录
let arr = ''
myAxios({
  url: 'https://blog.zifeiyu.love/info/collect',
  params: {
    id: '',
    page: 1,
    pageSize: 10
  },
  headers: {
    token: localStorage.getItem('token')
  }
}).then(result => {
  result.data.records.forEach(item => {
    myAxios({
      url: 'https://blog.zifeiyu.love/video/query',
      params: {
        id: item.episodeId
      },
      headers: {
        token: localStorage.getItem('token')
      }
    }).then(result => {
      arr += `
          <div class="history-item">
            <img src="${result.data.cover}" alt="">
            <span>${result.data.name}</span>
          </div>
    `
      document.querySelector('.collect-body').innerHTML = arr
    })
  })
})

// 注销
document.querySelector('.setting-btn').addEventListener('click', () => {
  if (confirm('您确定要注销账号吗?')) {
    myAxios({
      url: 'https://blog.zifeiyu.love/user/logoff',
      headers: {
        token: localStorage.getItem('token')
      }
    }).then(() => {
      localStorage.removeItem('token')
      location.href = 'index.html'
    })
  }
})

// 名称头像
myAxios({
  url: 'https://blog.zifeiyu.love/info/query',
  headers: {
    token: localStorage.getItem('token')
  }
}).then(result => {
  document.querySelector('.nickname').innerHTML = result.data.username
  document.querySelector('.user-avatar img').src = result.data.avatar
  document.querySelector('.user img').src = result.data.avatar
})

// 切换头像
document.querySelector('.user-avatar').addEventListener('mouseenter', () => {
  document.querySelector('.toggle').style.visibility = 'visible'
})
document.querySelector('.user-avatar').addEventListener('mouseleave', () => {
  document.querySelector('.toggle').style.visibility = 'hidden'
})
document.querySelector('.user-avatar').addEventListener('click', () => {
  document.querySelector('.file').click()
})
document.querySelector('.file').addEventListener('change', () => {
  const file = document.querySelector('.file').files[0]
  if (!file) {
    return
  }
  const formData = new FormData()
  formData.append('file', file)
  myAxios({
    url: 'https://blog.zifeiyu.love/info/pic',
    method: 'post',
    headers: {
      token: localStorage.getItem('token')
    },
    data: formData
  }).then(result => {
    document.querySelector('.user-avatar img').src = result.data
    document.querySelector('.user img').src = result.data
    myAxios({
      url: 'https://blog.zifeiyu.love/user/modify',
      method: 'put',
      data: {
        isSeen: 1,
        avatar: result.data
      },
      headers: {
        token: localStorage.getItem('token')
      }
    }).then(result => {
      alert(result.data)
    })
  })
})




